﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sencha.Serialization.Bson.Serializers
{
    public sealed class BsonJavaScriptSerializer : TypeSerializer<BsonJavaScript>
    {
        public override BsonJavaScript Deserialize(IJsonReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            if (reader is IBsonReader)
				return this.DeserializeBson(reader as IBsonReader);

            reader.ReadObjectBegin();
            var code = reader.ReadMember<string>("$code");
            reader.ReadObjectEnd(false);

            var value = new BsonJavaScript(code);
            return value;
        }
		private BsonJavaScript DeserializeBson(IBsonReader reader)
        {
			if (reader.Token != BsonToken.JavaScript)
                throw new Exceptions.UnexpectedBsonToken(reader, BsonToken.JavaScript);

			var value = (BsonJavaScript)reader.Value.Raw;
            return value;
        }

        public override void Serialize(IJsonWriter writer, BsonJavaScript value)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");

            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            if (writer is IBsonWriter)
            {
				this.SerializeBson(writer as IBsonWriter, value);
                return;
            }

            writer.WriteObjectBegin();
            writer.WriteMember<string>("$code", value.Code);
            writer.WriteObjectEnd();
        }
		private void SerializeBson(IBsonWriter writer, BsonJavaScript value)
        {
            if (value == null)
                throw new ArgumentNullException("value");
            if (writer == null)
                throw new ArgumentNullException("writer");

            writer.Write(BsonToken.JavaScript, value);
        }
    }
}
